package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.OrgRistTypeEnum;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.fenxi.emums.RiskTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.framework.shiro.service.SysPasswordService;

/**
 * 首页 业务处理
 *
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IRiskLevelDataService riskLevelDataService;

    @Autowired
    private IROrgService rOrgService;

    @Autowired
    private IFireValueDataService iFireValueDataService;
    @Autowired
    private IActionValueDataService iActionValueDataService;
    @Autowired
    private IToolValueDataService iToolValueDataService;
    @Autowired
    private IVehicleValueDataCService iVehicleValueDataCService;

    @Autowired
    private ISysDictTypeService dictTypeService;


    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(configService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(configService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
        mmap.put("copyrightYear", RuoYiConfig.getCopyrightYear());
        mmap.put("demoEnabled", RuoYiConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登录");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(Long orgId,ModelMap mmap)
    {
        mmap.put("version", RuoYiConfig.getVersion());
        ROrg ROrg = new ROrg();
        SysUser sysUser = getSysUser();
        String deptName = sysUser.getDept().getDeptName();
        List<SysDictData> dept_name = dictTypeService.selectDictDataByType("fx_org");
        List<SysDictData> collect = dept_name.stream().filter(o -> o.getDictLabel().equals(deptName)).collect(Collectors.toList());
        if(!collect.isEmpty()){
            ROrg.setName(deptName);
        }
        List<ROrg> rOrgs = rOrgService.selectROrgList(ROrg);
        mmap.put("rOrgs", rOrgs);
        ROrg rOrg = rOrgService.selectROrgById(orgId);
        ROrg rOrg1 = rOrgService.selectROrgById(1L);
        mmap.put("org", Objects.isNull(rOrg)?rOrg1:rOrg);
        return "main";
    }

    @GetMapping("/system/timeline")
    public String timeline(Long id,String type,Integer lev,ModelMap mmap)
    {
        RiskLevelData riskLevelData0 = new RiskLevelData();
        riskLevelData0.setUnit(id);
        List<RiskLevelData> riskLevelData1 = riskLevelDataService.selectRiskLevelDataList(riskLevelData0);
        if(!riskLevelData1.isEmpty()){
            RiskLevelData riskLevelData = new RiskLevelData();
            BeanUtils.copyProperties(riskLevelData1.get(0),riskLevelData);
            ROrg rOrg = rOrgService.selectROrgById(id);
            riskLevelData.setOrg(rOrg.getName());
            riskLevelData.setRistType(Integer.parseInt(RiskTypeEnum.getCodeByinfo(type)));
            mmap.put("riskLevelData",riskLevelData);
        }
        List<ROrgRiskEvent> ROrgRiskEvents = new ArrayList<>();
        switch (RiskTypeEnum.getCodeByinfo(type)){
            case "1":
                List<RiskLevelData>   riskLevelDataDaoJue =  new ArrayList<>();
                for (RiskLevelData riskLevelData : riskLevelData1) {
                    if(riskLevelData.getRistType()==1){
                        riskLevelDataDaoJue.add(riskLevelData);
                    }
                }
                ROrgRiskEvents =  getROrgRiskEvents(ROrgRiskEvents,riskLevelDataDaoJue);
                break;
            case "2":
                List<RiskLevelData>   riskLevelDataDaoQie =  new ArrayList<>();
                for (RiskLevelData riskLevelData : riskLevelData1) {
                    if(riskLevelData.getRistType()==2){
                        riskLevelDataDaoQie.add(riskLevelData);
                    }
                }
                ROrgRiskEvents =  getROrgRiskEvents(ROrgRiskEvents,riskLevelDataDaoQie);
                break;
            case "3":
                List<RiskLevelData>   riskLevelDataHuozai =  new ArrayList<>();
                for (RiskLevelData riskLevelData : riskLevelData1) {
                    if(riskLevelData.getRistType()==3){
                        riskLevelDataHuozai.add(riskLevelData);
                    }
                }
                ROrgRiskEvents =  getROrgRiskEvents(ROrgRiskEvents,riskLevelDataHuozai);
                break;
            case "4":
                List<RiskLevelData>   riskLevelDataFaren =  new ArrayList<>();
                for (RiskLevelData riskLevelData : riskLevelData1) {
                    if(riskLevelData.getRistType()==4){
                        riskLevelDataFaren.add(riskLevelData);
                    }
                }
                ROrgRiskEvents =  getROrgRiskEvents(ROrgRiskEvents,riskLevelDataFaren);
                break;
        }
        mmap.put("ROrgRiskEvents",ROrgRiskEvents);
        mmap.put("id",id);
        mmap.put("lev",lev);
        return  "demo/form/timeline";
    }

    public  List<ROrgRiskEvent> getROrgRiskEvents(List<ROrgRiskEvent> ROrgRiskEvents,List<RiskLevelData> riskLevelDatas){
        for (RiskLevelData riskLevelData : riskLevelDatas) {
            String ss = riskLevelData.getAnomalousEventType();
            String[] arr = ss.split(",");
            for (String s : arr) {
                String[] arr1 = s.split(":");
                ROrgRiskEvent rOrgRiskEvent = new ROrgRiskEvent();
                switch (arr1[0]){
                    case "tool_ID":
                        Integer toolId = Integer.parseInt(arr1[1]);
                        ToolValueData toolValueData = iToolValueDataService.selectToolValueDataByActionId(toolId);
                        rOrgRiskEvent.setRiskType(toolValueData.getToolType());
                        rOrgRiskEvent.setCreateTime(toolValueData.getTime());
                        rOrgRiskEvent.setCoordinate(toolValueData.getCoordinate());
                        rOrgRiskEvent.setDevice(toolValueData.getDevice());
                        rOrgRiskEvent.setName("工具异常");
                        break;
                    case "action_ID":
                        Integer action_ID = Integer.parseInt(arr1[1]);
                        ActionValueData actionValueData = iActionValueDataService.selectActionValueDataByActionId(action_ID);
                        rOrgRiskEvent.setRiskType(actionValueData.getActionType());
                        rOrgRiskEvent.setCreateTime(actionValueData.getTime());
                        rOrgRiskEvent.setCoordinate(actionValueData.getCoordinate());
                        rOrgRiskEvent.setDevice(actionValueData.getDevice());
                        rOrgRiskEvent.setName("行人异常");
                        break;
                    case "vehicle_ID":
                        Integer vehicle_ID = Integer.parseInt(arr1[1]);
                        VehicleValueDataC vehicleValueDataC = iVehicleValueDataCService.selectVehicleValueDataCByVehicleId(vehicle_ID);
                        rOrgRiskEvent.setRiskType(vehicleValueDataC.getVehicleType());
                        rOrgRiskEvent.setCreateTime(vehicleValueDataC.getTime());
                        rOrgRiskEvent.setCoordinate(vehicleValueDataC.getCoordinate());
                        rOrgRiskEvent.setDevice(vehicleValueDataC.getDevice());
                        rOrgRiskEvent.setName("火灾异常");
                        break;
                    case "fire_ID":
                        Integer fire_ID = Integer.parseInt(arr1[1]);
                        FireValueData valueData = iFireValueDataService.selectFireValueDataByFireId(fire_ID);
                        rOrgRiskEvent.setRiskType(valueData.getFireType());
                        rOrgRiskEvent.setCreateTime(valueData.getTime());
                        rOrgRiskEvent.setCoordinate(valueData.getCoordinate());
                        rOrgRiskEvent.setDevice(valueData.getDevice());
                        rOrgRiskEvent.setName("火灾异常");

                }
                ROrgRiskEvents.add(rOrgRiskEvent);

            }
        }

        return ROrgRiskEvents;
    }

    // content-main class
    public String contentMainClass(Boolean footer, Boolean tagsView)
    {
        if (!footer && !tagsView)
        {
            return "tagsview-footer-hide";
        }
        else if (!footer)
        {
            return "footer-hide";
        }
        else if (!tagsView)
        {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
